package com.zhkj.txg.module.order.ui

import android.app.Activity
import android.content.Intent
import android.text.TextUtils
import android.view.View
import androidx.lifecycle.Observer
import com.bigkoo.pickerview.builder.OptionsPickerBuilder
import com.bigkoo.pickerview.listener.OnOptionsSelectListener
import com.bigkoo.pickerview.view.OptionsPickerView
import com.contrarywind.interfaces.IPickerViewData
import com.zhkj.lib.base.ViewModelActivity
import com.zhkj.lib.http.HttpResponseStatus
import com.zhkj.txg.R
import com.zhkj.txg.module.order.entity.AddressDetailEntity
import com.zhkj.txg.module.order.vm.AddressViewModel
import kotlinx.android.synthetic.main.activity_address_edit.*
import razerdp.util.KeyboardUtils

class AddressEditActivity : ViewModelActivity<AddressViewModel>() {

    companion object {
        private val TYPE = "type"
        private val ADDRESS_ID = "address"
        private val TYPE_ADD = 0
        private val TYPE_EDIT = 1

        fun addAddress(activity: Activity, requestCode: Int) {
            val intent = Intent(activity, AddressEditActivity::class.java).putExtra(TYPE, TYPE_ADD)
            activity.startActivityForResult(intent, requestCode)
        }

        fun editAddress(activity: Activity, addressId: Int, requestCode: Int) {
            val intent = Intent(activity, AddressEditActivity::class.java).putExtra(TYPE, TYPE_ADD)
                .putExtra(TYPE, TYPE_EDIT).putExtra(ADDRESS_ID, addressId)
            activity.startActivityForResult(intent, requestCode)
        }
    }

    private var type: Int = TYPE_ADD

    private val option: OptionsPickerView<IPickerViewData> by lazy {
        OptionsPickerBuilder(this,
            OnOptionsSelectListener { options1, options2, options3, _ ->
                viewModel.provinceList?.let {
                    val provinceEntity = it[options1]
                    val cityEntity = provinceEntity.cityList[options2]
                    val areaEntity = cityEntity.areaList[options3]
                    with(viewModel.selectProvince) {
                        provinceId = provinceEntity.provinceId
                        provinceName = provinceEntity.provinceName
                        cityId = cityEntity.cityId
                        cityName = cityEntity.cityName
                        areaId = areaEntity.id
                        areaName = areaEntity.areaName
                    }
                    tvAddressArea.text = buildString {
                        append(provinceEntity.provinceName).append(cityEntity.cityName).append(areaEntity.areaName)
                    }
                }
            }).build<IPickerViewData>()
    }

    override fun setViewModel(): AddressViewModel = createViewModel()
    override fun statusTitleBar(): View? = titleAddress
    override val layoutResId: Int = R.layout.activity_address_edit

    override fun initViewModel() {
        // 添加收货地址数据观察者
        viewModel.addAddressLiveData.observe(this, Observer {
            handlerResponseStatus(it.status, it.statusTip)
            if (it.status == HttpResponseStatus.Status.SUCCESS) {
                toast(getString(R.string.address_save_success))
                setResult(Activity.RESULT_OK)
                finish()
            }
        })
        // 收货地址详情数据观察者
        viewModel.addressDetailLiveData.observe(this, Observer { it ->
            handlerResponseStatus(it.status, it.statusTip)
            if (it.status == HttpResponseStatus.Status.SUCCESS) {
                it.response?.data?.let {
                    etAddressName.setText(it.consignee)
                    etAddressMobile.setText(it.mobile)
                    etAddressDetailArea.setText(it.address)
                    tvAddressArea.text = viewModel.queryAddressString(it.province, it.city, it.district)
                    defaultSwitch.isChecked = it.isDefault
                    if (it.gender == 1) btnMale.isChecked = true
                    else btnFemale.isChecked = true
                }
            }
        })
        viewModel.deleteAddressLiveData.observe(this, Observer {
            handlerResponseStatus(it.status, it.statusTip)
            if (it.status == HttpResponseStatus.Status.SUCCESS) {
                toast(getString(R.string.address_delete_success))
                setResult(Activity.RESULT_OK)
                finish()
            }
        })
    }

    override fun initUI() {
        type = intent.getIntExtra(TYPE, TYPE_ADD)
        btnAddAddress.visibility = if (type == TYPE_ADD) View.VISIBLE else View.GONE
        btnSaveAddress.visibility = if (type == TYPE_EDIT) View.VISIBLE else View.GONE
        btnDeleteAddress.visibility = if (type == TYPE_EDIT) View.VISIBLE else View.GONE

        //弹出省市区选择框
        tvAddressArea.setOnClickListener {
            viewModel.provinceUIData?.let {
                if (KeyboardUtils.isOpen()) KeyboardUtils.close(this)
                option.setPicker(it.provinceUIList, it.cityUIList, it.areaUIList)
                option.show()
            }
        }
        // 添加收货地址
        btnAddAddress.setOnClickListener {
            if (isParamValid()) viewModel.addAddress(
                AddressDetailEntity(
                    0, etAddressName.text!!.toString(), etAddressMobile.text!!.toString(), "",
                    viewModel.selectProvince.provinceId, viewModel.selectProvince.cityId,
                    viewModel.selectProvince.areaId, etAddressDetailArea.text!!.toString(), defaultSwitch.isChecked,
                    if (btnMale.isChecked) 1 else 2
                )
            )
        }
        // 保存收货地址
        btnSaveAddress.setOnClickListener {
            if (isParamValid()) viewModel.addAddress(
                AddressDetailEntity(
                    intent.getIntExtra(ADDRESS_ID, 0), etAddressName.text!!.toString(),
                    etAddressMobile.text!!.toString(), "", viewModel.selectProvince.provinceId,
                    viewModel.selectProvince.cityId, viewModel.selectProvince.areaId,
                    etAddressDetailArea.text!!.toString(), defaultSwitch.isChecked,
                    if (btnMale.isChecked) 1 else 2
                )
            )
        }
        // 删除收货地址
        btnDeleteAddress.setOnClickListener {
            viewModel.deleteAddress(intent.getIntExtra(ADDRESS_ID, 0).toLong())
        }
    }

    override fun initData() {
        viewModel.getProvinceFromAssets(if (type == TYPE_EDIT) intent.getIntExtra(ADDRESS_ID, 0) else 0)
    }

    private fun isParamValid(): Boolean {
        if (TextUtils.isEmpty(etAddressName.text)) {
            toast(getString(R.string.consignee_invalid))
            return false
        }
        if (TextUtils.isEmpty(etAddressMobile.text) || etAddressMobile.text!!.length < 11) {
            toast(getString(R.string.mobile_invalid))
            return false
        }
        if (viewModel.selectProvince.provinceId == 0 ||
            viewModel.selectProvince.cityId == 0 ||
            viewModel.selectProvince.areaId == 0
        ) {
            toast(getString(R.string.province_invalid))
            return false
        }
        if (TextUtils.isEmpty(etAddressDetailArea.text)) {
            toast(getString(R.string.address_invalid))
            return false
        }
        return true
    }
}